package apigateway.project.core;

import lombok.extern.slf4j.Slf4j;

import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;
import static apigateway.project.commen.utils.ConfigUtils.toConfig;

/**
 * 配置加载类
 */
@Slf4j
public class ConfigLoader {
    private static final String CONFIG_FILE = "gateway.properties";
    private static final ConfigLoader INSTANCE = new ConfigLoader();
    //不允许通过构造函数实例化
    private ConfigLoader() {}
    //提供静态方法实例化
    public static ConfigLoader getInstance() {
        return INSTANCE;
    }
    private Config config;

    public Config getConfig() {
        return INSTANCE.getConfig();
    }

    public Config loadConfig(String args[]){
        //默认值
        this.config = new Config();

        //通过配置文件配置
        loadFromFile();

        return config;
    }

    private void loadFromFile() {
        InputStream in = ConfigLoader.class.getResourceAsStream(CONFIG_FILE);
        if(in != null) {
            Properties prop = new Properties();
            try {
                //将文件读入properties对象中
                prop.load(in);
                //将prop中的配置信息(键值对)填充到config中
                toConfig(prop,config);
            } catch (IOException e) {
                log.error("Failed to load properties from " + CONFIG_FILE, e);
            }finally {
                //关闭文件
                try {
                    in.close();
                } catch (IOException e) {}
                }
            }
        }



    }


